/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import entity.RegisteredUser;
import java.io.IOException;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import manager.RegisteredUserManager;
import utils.FacesUtils;
import utils.HashGenerator;

/**
 * This bean is used for the purposes of handling and verifying logins and attaching objects
 * to the session scope. It also has the parameter next from the url to redirect to after successful login
 * This bean is used on the index.jsp page
 */
@ManagedBean
@RequestScoped
public class LoginBean implements Serializable {

    @ManagedProperty("#{registeredUserBean}")
    protected RegisteredUserBean rub;
    protected String username;
    protected String password;
    @ManagedProperty(value = "#{param['next']}")
    protected String next;

    /** Creates a new instance of LoginBean */
    public LoginBean() {
    }

    public String login() {
        System.out.println("Login Invoked");
        RegisteredUserManager rum = new RegisteredUserManager();
        RegisteredUser registeredUser;
        if (username.length() != 0 && password.length() != 0) {
            registeredUser = rum.validateLogin(username,  HashGenerator.generateHash(password));
            //registeredUser = rum.validateLogin(username,  password);
            if (registeredUser != null) {
                rub.setLoggedIn(true);
                rub.setRegisteredUser(registeredUser);

                System.out.println("Successfull Login");
                if (next != null) {
                    try {
                        FacesContext.getCurrentInstance().getExternalContext().redirect(next);
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                return "home";
            } else {
                System.out.println("No such username");
                FacesUtils.throwFacesException("login", "Username and password don't match", FacesContext.getCurrentInstance());
            }
        }
        return null;
    }

    public String getNext() {
        return next;
    }

    public void setNext(String next) {
        this.next = next;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public RegisteredUserBean getRub() {
        return rub;
    }

    public void setRub(RegisteredUserBean rub) {
        this.rub = rub;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
